package com.tbl.modules.wms.controller.system;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.tbl.common.utils.PageTbl;
import com.tbl.common.utils.PageUtils;
import com.tbl.common.utils.StringUtils;
import com.tbl.modules.les.constant.Const;
import com.tbl.modules.platform.constant.MenuConstant;
import com.tbl.modules.platform.controller.AbstractController;
import com.tbl.modules.platform.entity.system.Role;
import com.tbl.modules.platform.entity.system.User;
import com.tbl.modules.platform.service.system.RoleService;
import com.tbl.modules.platform.service.system.UserService;
import com.tbl.modules.wms.service.baseinfo.FactoryAreaService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 用户控制层
 * @author 70486
 */
@Controller
@RequestMapping(value = "/user")
public class UserController extends AbstractController {

    /**
     * 用户service
     */
    @Autowired
    private UserService userService;
    /**
     * 角色service
     */
    @Autowired
    private RoleService roleService;
    /**
     * 厂区信息service
     */
    @Autowired
    private FactoryAreaService factoryAreaService;

    /**
     * 用户设置：修改用户密码
     * @param oldPass 旧密码
     * @param newPass 新密码
     * @return Map<String,Object>
     */
    @RequestMapping(value = "/updateUserPass")
    @ResponseBody
    public Map<String, Object> updateUserPass(String oldPass, String newPass) {
        String username = this.getSessionUser().getUsername();
        Map<String, Object> map = Maps.newHashMap();
        if (userService.getByUserName(username) > 0) {
            //先判断旧密码是否正确
            map = this.updateUserPass(this.getSessionUser().getUserId(), oldPass, newPass, userService.findByUsername(username).getUsername());
        }
        return map;
    }
    
    /**
     * 跳转到用户列表页面
     * @return ModelAndView
     */
    @RequestMapping(value = "/toList.do")
    @ResponseBody
    public ModelAndView toList() {
        ModelAndView mv = new ModelAndView();
        mv.addObject("operationCode", roleService.selectOperationByRoleId(getSessionUser().getRoleId(), MenuConstant.user));
        mv.setViewName("techbloom/system/user/user_list");
        return mv;
    }

    /**
     * 获取用户列表数据
     * @param queryJsonString 查询条件
     * @return Object 用户列表数据
     */
    @RequestMapping(value = "/list.do")
    @ResponseBody
    public Object listUsers(String queryJsonString) {
    	Map<String, Object> map = new HashMap<>(7);
        if (!StringUtils.isEmpty(queryJsonString)) {
            map = JSON.parseObject(queryJsonString);
        }
        PageTbl page = this.getPage();
        map.put("page", page.getPageno());
        map.put("limit", page.getPagesize());
        String sortName = page.getSortname();
        if (StringUtils.isEmptyString(sortName)) {
            sortName = "user_id";
            page.setSortname(sortName);
        }else if("REMARK".equals(sortName)) {
        	sortName = "a.REMARK";
            page.setSortname(sortName);
        }
        String sortOrder = page.getSortorder();
        if (StringUtils.isEmptyString(sortOrder)) {
            sortOrder = "desc";
            page.setSortorder(sortOrder);
        }
        map.put("sidx", page.getSortname());
        if ("rolename".equals(page.getSortname())) {
            map.put("sidx", "role_name");
        }
        map.put("order", page.getSortorder());
        map.put("suserid", getUserId());
        PageUtils pageUser = userService.queryPage(map);
        page.setTotalRows(pageUser.getTotalCount() == 0 ? 1 : pageUser.getTotalCount());
        map.put("rows", pageUser.getList());
        executePageMap(map, page);
        return map;
    }

    /**
     * 在session中获取当前用户
     * @return User 用户
     */
    @RequestMapping(value = "/getSessionUser")
    @ResponseBody
    @Override
    public User getSessionUser() {
        return super.getSessionUser();
    }

    /**
     * 判断用户类型
     * @return List<Map<String,Object>>
     */
    @RequestMapping(value = "/getUserMenu")
    @ResponseBody
    public List<Map<String, Object>> getUserMenu() {
        //判断用户是供应闪还是系统用户
        return userService.getByUserName(this.getSessionUser().getUsername())>0?userService.getUserMenu(getUserId(),"0"):
                userService.getUserMenu(getUserId(),"1");
    }

    /**
     * 判断用户类型
     * @return List<Map<String, Object>>
     */
    @RequestMapping(value = "/getUserMenu11")
    @ResponseBody
    public List<Map<String, Object>> getUserMenu11() {
        //判断用户是供应商还是系统用户
        return userService.getByUserName(this.getSessionUser().getUsername())>0 ? userService.getUserMenu11(getUserId(),"0") :
                userService.getUserMenu11(getUserId(),"1");
    }

    /**
     * 保存自定义导航菜单
     * @param menus 菜单
     * @return boolean
     */
    @RequestMapping(value = "/setUserMenu")
    @ResponseBody
    public boolean setUserMenu(String menus) {
        //判断用户是供应商还是系统用户
        return userService.getByUserName(this.getSessionUser().getUsername()) > 0 ? userService.setUserMenu(menus, getUserId()) :
                userService.setUserMenus(menus, getUserId());
    }

    /**
     * 设置快捷菜单
     * @param menus 菜单
     * @return boolean
     */
    @RequestMapping(value = "/setUserQuickMenu")
    @ResponseBody
    public boolean setUserQuickMenu(String menus) {
        //判断用户是供应商还是系统用户
        return userService.getByUserName(this.getSessionUser().getUsername()) > 0 ? userService.setUserQuickMenu(menus, getUserId()) :
                userService.setUserQuickMenus(menus, getUserId());
    }

    /**
     * 返回到用户添加页面
     * @return ModelAndView
     */
    @RequestMapping(value = "/user_add")
    public ModelAndView userAdd() {
        ModelAndView mv=this.getModelAndView();
        mv.addObject("factlist",factoryAreaService.getFactoryList());
        mv.setViewName("techbloom/system/user/user_add");
        return mv;
    }
    
    /**
     * 更新个人资料
     * @param name 姓名
     * @param email 邮箱
     * @param phone 电话
     * @param remark 备住
     * @return Map<String,Object>
     */
    @RequestMapping(value = "/updateUserInfo")
    @ResponseBody
    public Map<String,Object> updateUserInfo(String name,String email,String phone,String remark){
    	Map<String,Object> map = new HashMap<>(2);
    	User user = getSessionUser();
    	user.setName(name);
    	user.setEmail(email);
    	user.setPhone(phone);
    	user.setRemark(remark);
    	boolean result = userService.updateById(user);
    	map.put("result", result);
    	map.put("msg", result?"保存成功！":"保存失败！");
    	return map;
    }

    /**
     * 保存/修改用户
     * @param user 用户
     * @param userFactoryIds 所属厂或仓库
     * @return Map<String,Object>
     */
    @RequestMapping(value = "/save")
    @ResponseBody
    public Map<String, Object> save(User user,String userFactoryIds) {
        Map<String, Object> map = Maps.newHashMap();
        if (user != null&&user.getUserId() == null){
            //新增：密码加密
            user.setPassword(new SimpleHash("SHA-1", user.getPassword(), user.getUsername()).toString());
        }
        map.put("result", userService.saveU(user,userFactoryIds));
        return map;
    }

    /**
     * 返回到用户修改页面
     * @param id 用户主键
     * @return ModelAndView
     */
    @RequestMapping(value = "/user_edit")
    public ModelAndView userEdit(Long id) {
    	ModelAndView mv = new ModelAndView();
    	User user = new User();
    	if(id!=null) {
    	    user = userService.selectById(id);
        }
    	if(user.getRoleId()!=null) {
    		Role role = roleService.selectById(user.getRoleId());
    		user.setRoleno(role.getRoleId().toString());
    		user.setRolename(role.getRoleName());
    	}
    	mv.addObject("user", user);
    	//获取厂区信息列表
    	mv.addObject("factlist",factoryAreaService.getFactoryList());
    	//获取编辑时人员的所属厂区
        List<String> factRelList = new ArrayList<>();
        if(user.getFactoryCode() != null){
            factRelList=Arrays.asList(user.getFactoryCode().split(","));
        }
        mv.addObject("factRelList",factRelList);
        mv.setViewName("techbloom/system/user/user_edit");
        return mv;
    }

    /**
     * 根据用户主键获取用户信息
     * @param userId 用户主键
     * @return User 用户
     */
    @RequestMapping(value = "/getUser")
    @ResponseBody
    public User getUserById(long userId) {
        return userService.findByUserId(userId + "");
    }

    /**
     * 获取用户所属的厂区
     * @param userId 用户主键
     * @return Map<String,Object>
     */
    @RequestMapping(value = "/getUser1")
    @ResponseBody
    public Map<String,Object> getUserById1(Long userId) {
        return new HashMap<String, Object>(1){{
            put("factoryCode", factoryAreaService.getFactoryInfo(Arrays.asList(userService.findByUserId(userId + "").getFactoryCode().split(","))));
        }};
    }

    /**
     * 判断用户名是否存在
     * @return boolean
     */
    @RequestMapping(value = "/hasU.do")
    @ResponseBody
    public boolean hasU() {
        boolean errInfo = false;
        try {
            if (userService.findByUId(this.getPageData()) == null) {
                errInfo = true;
            }
        } catch (Exception e) {
            logger.error(e.toString(), e);
        }
        return errInfo;
    }

    /**
     * 初始化用户密码，根据用户主键，初始化用户密码，即将用户密码修改为123456
     * @param userID 用户主键
     * @return boolean
     */
    @RequestMapping(value = "/initUserPass")
    @ResponseBody
    public boolean initUserPass(Long userID) {
        return userService.updateUserColumn(userID, "PASSWORD", new SimpleHash("SHA-1", "123456",
                        userService.findByUserId(String.valueOf(userID)).getUsername()).toString());
    }

    /**
     * 用户删除
     * @param ids 用户主键
     * @return Boolean
     */
    @RequestMapping(value = "/delUById")
    @ResponseBody
    public Boolean delUById(String[] ids) {
        return userService.deleteBatchIds(Arrays.stream(StringUtils.join(ids, ",", true).replaceAll("'", "")
                .split(",")).map(s -> Long.parseLong(s.trim())).collect(Collectors.toList()));
    }

    /**
     * 停用、启用用户
     * @return Object
     */
    @RequestMapping(value = "/changeStat")
    @ResponseBody
    public Object changeStat() {
                                        // 要修改后的状态                              // 要修改状态的userid
        return userService.changeState(this.getPageData().getString("state"), this.getPageData().getString("ids[]"));
    }

    /**
     * 获取用户的角色和部门信息
     * @param userId 用户主键
     * @return Map<String, Object>
     */
    @RequestMapping(value = "/getSomeInfo")
    @ResponseBody
    public Map<String, Object> getUserRelship(Long userId) {
        Map<String, Object> map = Maps.newHashMap();
        if (userId!=null){
            User user = getUserById(userId);
            if (user != null) {
                map.put("dept", "");
                Role role = roleService.selectById(user.getRoleId());
                map.put("role", role);
                //给他个厂区编号
                map.put("factoryCode", user.getFactoryCode());
            }
        }
        return map;
    }

    /**
     * 导出Excel
     */
    @RequestMapping(value = "/toExcel")
    @ResponseBody
    public void artBomExcel() {
        userService.toExcel(response, "", userService.getAllLists(request.getParameter("ids")));
    }

    /**
     * 权限
     * @return Map<String, String>
     */
    public Map<String, String> getHC() {
        //shiro管理的session
        return (Map<String, String>) SecurityUtils.getSubject().getSession().getAttribute(Const.SESSION_QX);
    }

    /**
     * 判断是否有设备检测菜单访问权限
     * @return int
     */
    @RequestMapping(value = "/getMenuRightCount")
    @ResponseBody
    public int isHaveMonitorRight() {
        return userService.getJcMenuByUser(getSessionUser());
    }

    /**
     * 获取列表信息：下拉框使用
     * @param queryString
     * @param pageSize
     * @param pageNo
     * @param deptId
     * @return Map<String, Object>
     */
    @RequestMapping(value = "/getUserList")
    @ResponseBody
    public Map<String, Object> getUserList(String queryString, int pageSize, int pageNo, String deptId) {
        Map<String, Object> map = new HashMap<>(6);
        if (!StringUtils.isEmpty(queryString)) {
            map = JSON.parseObject(queryString);
        }
        map.put("page", pageNo);
        map.put("limit", pageSize);
        map.put("deptId", deptId);
        PageUtils pageUser = userService.getUserPageList(map);
        map.put("result", userService.getLstMapUser(map));
        map.put("total", pageUser.getTotalCount());
        return map;
    }


    /**
     * 获取可以添加的用户(下拉框使用，模糊查询结果)
     * @param queryString
     * @param pageNo
     * @param pageSize
     * @return Map<String, Object>
     */
    @RequestMapping(value = "/getUserSelect")
    @ResponseBody
    public Map<String, Object> getUserSelect(String queryString, int pageNo, int pageSize) {
        Map<String, Object> map = new HashMap<>(2);
        List<Map<String, Object>> ulist;
        PageTbl page = this.getPage();
        page.setPageno(pageNo);
        page.setPagesize(pageSize);
        Page<Map<String, Object>> pageMap = userService.getUserSelect(page, queryString);
        ulist = pageMap.getRecords();
        map.put("result", ulist == null ? "" : ulist);
        map.put("total", userService.selectCount(new EntityWrapper<User>().like("username", queryString)));
        return map;
    }
    
    /**
     * 修改用户密码
     * @param userId  用户主键
     * @param oldPass 旧密码
     * @param newPass 新密码
     * @param salt    加密使用的salt值（加密时要使用相同的salt，才能确保旧密码加密之后，与之前加密的密码相同）
     * @return Map<String, Object>
     */
    @RequestMapping(value = "/updatePassWordById")
    @ResponseBody
    public Map<String, Object> updateUserPass(Long userId, String oldPass, String newPass, String salt) {
        //存放操作结果，和提示信息
        Map<String, Object> map = Maps.newHashMap();
        boolean isSuccess = false;
        if (userId != null) {
            //如果要修改密码
            //先判断旧密码是否正确
            User oldUser = userService.findByUserId(String.valueOf(userId));
            //使用用户输入的旧密码加密得到加密后的密码
            //String simpleHash =new SimpleHash("SHA-1", str, salt).toString();
            if (oldUser != null) {
                String oldHashPass = new SimpleHash("SHA-1", oldPass, oldUser.getUsername()).toString();
                //判断加密的密码和之前的加密的密码是否相等：相等则表示密码正确，可以修改密码
                String mapDatakey = "data";
                if (oldUser.getPassword().equalsIgnoreCase(oldHashPass)) {
                    //用户输入的旧密码正确，可以修改密码,使用用户输入的新密码
                    if (!StringUtils.isEmptyString(newPass)) {
                        String newHashPass = new SimpleHash("SHA-1", newPass, salt).toString();
                        if (newHashPass.equalsIgnoreCase(oldHashPass)) {
                            //与老密码相同，给出提示，不能与老密码相同
                            map.put(mapDatakey, "不能与旧密码相同！");
                        } else {
                            //可以修改密码
                            isSuccess = userService.updateUserColumn(userId, "PASSWORD", newHashPass);
                            map.put(mapDatakey, isSuccess ? "密码修改成功！" : "密码修改失败！");
                        }
                    }
                } else {
                    //密码不正确，不可以修改密码
                    map.put(mapDatakey, "密码错误！");
                }
            }
        }
        //存放在map中的两个值的key：结果，提示信息
        String mapResultkey = "result";
        map.put(mapResultkey, isSuccess);
        return map;
    }

    /**
     * 返回到选择厂区仓库权限页面
     * @return String
     */
    @RequestMapping(value = "/roleEdit")
    public String roledit() {
        return "techbloom/system/user/user_role";
    }

    /**
     * 根据用户主键获取角色厂区、仓库权限
     * @param userId 用户主键
     * @param type 1成品用户；2原材料用户
     * @return List<Map>
     */
    @RequestMapping(value = "/getUserRoleByUserId")
    @ResponseBody
    public List<Map<String, Object>> getUserRoleByUserId(Long userId,Integer type) {
        List<Map<String, Object>> list;
        if (userId != null) {
            list = userService.getUserRoleByUserId(userId,type);
            Map<String, ? extends Object> rootm = ImmutableMap.of("id", "M0", "pId", "M-1", "name", "所有权限", "checked", false);
            List<Map<String, Object>> alllist = Lists.newArrayList();
            alllist.add((Map<String, Object>) rootm);
            alllist.addAll(list);
            return alllist;
        } else {
            list = userService.getUserRoleByUserIdTwo(type);
        }
        return list;
    }

    /**
     * 根据角色主键获取角色所属的厂区、仓库信息
     * @param userId 用户主键
     * @return User
     */
    @RequestMapping(value = "/getUserRoleById")
    @ResponseBody
    public User getUserRoleById(Long userId) {
        User user = null;
        if (userId != null){
            user = userService.selectById(userId);
        }
        return user;
    }

}
